package com.shanshan.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanshan.system.entity.Admin;
import com.shanshan.system.entity.Permission;
import com.shanshan.system.mapper.AdminMapper;
import com.shanshan.system.mapper.PermissionMapper;
import com.shanshan.system.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shanshan.system.util.JwtUtil;
import com.shanshan.system.util.WebUtil;
import com.shanshan.system.vo.Result;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shanshan
 * @since 2023-01-31
 */
@ToString
@SuppressWarnings("all")
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private AdminMapper adminMapper;
    @Override
    public Result sysMenuList() {
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> map = JwtUtil.decodeJWT(token);
        String username = (String) map.get("username");
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("account",username);
        Admin admin = adminMapper.selectOne(wrapper);
        List<Permission> sysMenus = permissionMapper.selectAll(admin.getId());
        List<Permission> menuList = hierarchy(sysMenus);
        return new Result(200,"查询成功",menuList);
    }

    /**
     * 建立菜单
     * @param permissionList
     * @return
     */
    private List<Permission> hierarchy(List<Permission> sysMenus){

        //1.一级菜单
        List<Permission> firsts=new ArrayList<>();
        for (Permission permission:sysMenus){
            if(permission.getMenuParentId()==0){
                firsts.add(permission);
            }
        }

        //2.查询一级菜单下的二级菜单
        for(Permission first:firsts){
            List<Permission> children=new ArrayList<>();
            for(Permission p:sysMenus){
                if(first.getId().equals(p.getMenuParentId())){
                    children.add(p);
                }
            }
            first.setChildren(children);
        }

        return firsts;
    }
}
